﻿using LoveEatRabbit.API.Read.Applications.Commands.Roles;
using LoveEatRabbit.API.Read.DTOS;
using LoveEatRabbit.Domain.RBAC;
using LoveEatRabbit.ErrorCode;
using LoveEatRabbit.Infrastructure.Interfaces;
using LoveEatRabbit.Infrastructure.Migrations;
using MediatR;

namespace LoveEatRabbit.API.Read.Applications.CommandHandlers.Roles
{
    public class RolePerQueryCommandHandler : IRequestHandler<RolePerQueryCommand, APIResult<APIPaging<RolePerDTO>>>
    {
        private readonly IBaseRespository<RoleModel> roleRep;
        private readonly IBaseRespository<PermissionModel> perRep;
        private readonly IBaseRespository<RolePermissionModel> rpRep;

        public RolePerQueryCommandHandler(IBaseRespository<RoleModel> roleRep, 
            IBaseRespository<PermissionModel> perRep, 
            IBaseRespository<RolePermissionModel> rpRep)
        {
            this.roleRep = roleRep;
            this.perRep = perRep;
            this.rpRep = rpRep;
        }

        public Task<APIResult<APIPaging<RolePerDTO>>> Handle(RolePerQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<RolePerDTO>> result = new APIResult<APIPaging<RolePerDTO>>(); 
            result.Code=APIResultCode.查询成功;
            result.Message=APIResultCode.查询成功.ToString();

            var res = from a in roleRep.GetAll()
                      join b in rpRep.GetAll() on a.RoleId equals b.RoleId
                      join c in perRep.GetAll() on b.PermissionId equals c.PermissionId
                      where !a.IsDeleted
                      select new RolePerDTO
                      {
                          RoleName=a.RoleName,
                          States=a.States,
                          CreatedTime=a.CreatedTime,
                          PermissionName=c.PermissionName,
                          PermissionURL= c.PermissionURL,
                          Index=c.Index,
                          RPId=b.RPId,
                          RoleId= a.RoleId,
                          PermissionId=c.PermissionId

                      };
            //角色名称模糊查询
            if (!string.IsNullOrEmpty(request.RoleName))
            {
                res=res.Where(x=>x.RoleName.Contains(request.RoleName));
            }
            //总条数
            var totalCount=res.Count();
            //总页数
            var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.Pagsize);
            //排序
            res = res.OrderByDescending(x => x.RoleId).Skip((request.Indpage - 1) * request.Pagsize).Take(request.Pagsize);

            APIPaging<RolePerDTO> paging = new APIPaging<RolePerDTO>();
            paging.TotalCount = totalCount;
            paging.TotalPage = totalPage;
            paging.Fdata=res.ToList ();
            result.Data = paging;


            return Task.FromResult(result);
        }
    }
}
